const connection = require('../../sql');

class TempFileService {
  async createTempFile({ sys_file_id, temp_name, url, remark, create_id, update_id }) {
    try {
      const now = new Date();
      const sql = `
        INSERT INTO sys_temp_file (
          sys_file_id, temp_name, url, remark,
          create_id, create_time, update_id, update_time
        )
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
      `;
      const [result] = await connection.execute(sql, [
        sys_file_id || null,
        temp_name,
        url,
        remark || null,
        create_id,
        now,
        null,
        null
      ]);
      return { id: result.insertId };
    } catch (error) {
      throw error;
    }
  }

  async deleteTempFiles(ids) {
    try {
      const sql = `
        DELETE FROM sys_temp_file
        WHERE id IN (${ids.map(() => '?').join(',')})
      `;
      const [result] = await connection.execute(sql, ids);
      if (result.affectedRows === 0) {
        throw new Error('没有可删除的模板文件');
      }
      return { success: true };
    } catch (error) {
      throw error;
    }
  }

  async updateTempFile({ id, sys_file_id, temp_name, url, remark, update_id }) {
    try {
      const sql = `
        UPDATE sys_temp_file
        SET
          sys_file_id = ?, temp_name = ?, url = ?,
          remark = ?, update_id = ?, update_time = ?
        WHERE id = ?
      `;
      const now = new Date();
      const [result] = await connection.execute(sql, [sys_file_id || null, temp_name, url, remark || null, update_id, now, id]);
      if (result.affectedRows === 0) {
        throw new Error('模板文件不存在');
      }
      return { success: true };
    } catch (error) {
      throw error;
    }
  }

  async getTempFileList({ page, limit, temp_name }) {
    const offset = (page - 1) * limit;
    let whereClause = '';
    const params = [];

    if (temp_name) {
      whereClause += ' AND t.temp_name LIKE ?';
      params.push(`%${temp_name}%`);
    }

    const countSql = `
      SELECT COUNT(*) as count
      FROM sys_temp_file t
      WHERE 1=1 ${whereClause}
    `;
    const listSql = `
      SELECT 
        t.id, t.sys_file_id, t.temp_name, t.url, t.remark,
        t.create_id, t.create_time, t.update_id, t.update_time,
        creator.username AS create_username,
        updater.username AS update_username
      FROM sys_temp_file t
      LEFT JOIN sys_user creator ON t.create_id = creator.id AND creator.del_flag = 'F'
      LEFT JOIN sys_user updater ON t.update_id = updater.id AND updater.del_flag = 'F'
      WHERE 1=1 ${whereClause}
      ORDER BY t.create_time DESC
      LIMIT ? OFFSET ?
    `;

    try {
      const [countResult] = await connection.execute(countSql, params);
      const [rows] = await connection.execute(listSql, [...params, String(limit), String(offset)]);
      return {
        current: page,
        limit,
        totalPage: Math.ceil(countResult[0].count / limit) || 1,
        total: countResult[0].count,
        rows
      };
    } catch (error) {
      throw error;
    }
  }

  async getTempFileInfo(id) {
    const sql = `
      SELECT 
        t.id, t.sys_file_id, t.temp_name, t.url, t.remark,
        t.create_id, t.create_time, t.update_id, t.update_time,
        creator.username AS create_username,
        updater.username AS update_username
      FROM sys_temp_file t
      LEFT JOIN sys_user creator ON t.create_id = creator.id AND creator.del_flag = 'F'
      LEFT JOIN sys_user updater ON t.update_id = updater.id AND creator.del_flag = 'F'
      WHERE t.id = ?
    `;

    try {
      const [rows] = await connection.execute(sql, [id]);
      if (rows.length === 0) {
        throw new Error('模板文件不存在');
      }
      return rows[0];
    } catch (error) {
      throw error;
    }
  }

  async getTempFileDropdown() {
    const sql = `
      SELECT id, temp_name, url
      FROM sys_temp_file
      ORDER BY create_time DESC
    `;

    try {
      const [rows] = await connection.execute(sql);
      return rows;
    } catch (error) {
      throw error;
    }
  }
}

module.exports = new TempFileService();
